package com.cqjtu.drive.controller;

import com.cqjtu.drive.pojo.RegistrationForm;
import com.cqjtu.drive.response.Response;
import com.cqjtu.drive.service.RegistrationFormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

/**
 * @Author zxl
 * @Date 2024/6/17 20:45
 */

@RestController
public class RegistrationFormController {

    String sId;

    @Autowired
    RegistrationFormService registrationFormService;

    @PostMapping("/api/getsId")
    public void getsid(@RequestParam String id) {
        sId = id;
    }

    @PostMapping("/api/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传的文件为空";
        }
        String uploadDir = "D:\\driveinfo\\" + sId + "\\";
        try {
            File destFile = new File(uploadDir + file.getOriginalFilename());
            file.transferTo(destFile);
            return "文件上传成功: " + destFile.getAbsolutePath();
        } catch (IOException e) {
            return "上传文件时发生错误: " + e.getMessage();
        }
    }

    @PostMapping("/api/download")
    public Integer handleFileDownload(@RequestParam String id) {
        String sourceDir = "D:\\driveinfo\\" + id + "\\体检.pdf";
        String destinationDir = "D:\\temp";

        File sourceFile = new File(sourceDir);
        if (!sourceFile.exists()) {
            return 1;
        }

        File destinationPath = new File(destinationDir);
        if (!destinationPath.exists()) {
            destinationPath.mkdirs(); // 如果目标目录不存在，则递归创建目录
        }

        Path destinationFilePath = Paths.get(destinationDir,sourceFile.getName());
        try {
            Files.copy(sourceFile.toPath(), destinationFilePath);
//            return "文件下载成功: " + destinationFilePath.toString();
            return 1;
        } catch (IOException e) {
            return 1;
        }
    }

    @PostMapping("/api/RegistrationForm/insert")
    public Response<String> insertOne(@RequestBody Map<String, String> map) {
        return registrationFormService.insertRegistrationForm(map);
    }

    @PostMapping("/api/RegistrationForm/getone")
    public Response<RegistrationForm> getOne(@RequestParam String rId) {
        return registrationFormService.getOne(rId);
    }


}
